package com.generate.control;

import java.awt.Component;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.util.ArrayList;
import java.util.List;

import javax.swing.JCheckBoxMenuItem;
import javax.swing.JPopupMenu;

import com.generate.library.DelayTask;


public class JMultiSelectReplace extends JTextFieldReplace implements IMultiValue
{
	/**
	 * 
	 */
	private static final long serialVersionUID = 1L;
	private JPopupMenu popupMenu;
	private final List<JCheckBoxMenuItem> lstMenuItems = new ArrayList<JCheckBoxMenuItem>();

	public JMultiSelectReplace()
	{
		super();
		addMouseListener(new MouseAdapter()
		{
			@Override
			public void mouseClicked(MouseEvent e)
			{
				popupMenu.show(JMultiSelectReplace.this, 0, JMultiSelectReplace.this.getHeight());
			}
		});
		popupMenu = new JPopupMenu()
		{
			/**
			 * 
			 */
			private static final long serialVersionUID = 1L;

			public void setVisible(boolean b)
			{
				super.setVisible(b);
				new DelayTask()
				{

					@Override
					public void run()
					{
						String text = "";
						for (JCheckBoxMenuItem item : lstMenuItems)
						{
							if (item.isSelected())
							{
								text += item.getText() + ", ";
							}
						}
						text = text.length() < 2 ? "" : text.substring(0, text.length() - 2);
						JMultiSelectReplace.this.setText(text);
					}
				}.delay(100);
			};
		};
		addPopup(this, popupMenu);
	}

	private static void addPopup(Component component, final JPopupMenu popup)
	{
		component.addMouseListener(new MouseAdapter()
		{
			public void mousePressed(MouseEvent e)
			{
				if (e.isPopupTrigger())
				{
					showMenu(e);
				}
			}

			public void mouseReleased(MouseEvent e)
			{
				if (e.isPopupTrigger())
				{
					showMenu(e);
				}
			}

			private void showMenu(MouseEvent e)
			{
				popup.show(e.getComponent(), e.getX(), e.getY());
			}
		});
	}

	private String[] items;

	@Override
	public String[] getItems()
	{
		JCheckBoxMenuItem chckbxmntmNewCheckItem = new JCheckBoxMenuItem("New check item");
		popupMenu.add(chckbxmntmNewCheckItem);
		items = new String[lstMenuItems.size()];
		for (int i = 0; i < lstMenuItems.size(); i++)
		{
			items[i] = lstMenuItems.get(i).getText();
		}
		return items;
	}

	@Override
	public void setItems(String[] items)
	{
		this.items = items;
		popupMenu.removeAll();
		for (String item : items)
		{
			JCheckBoxMenuItem boxMenuItem = new JCheckBoxMenuItem(item);
			popupMenu.add(boxMenuItem);
			lstMenuItems.add(boxMenuItem);
		}
	}
}
